package com.exm.mqttservice;

import org.eclipse.paho.client.mqttv3.*;

public class SimpleMqttConsumer {

    private static final String BROKER = "tcp://47.98.117.180:1883";  // MQTT 服务器地址
    private static final String TOPIC = "sensor/data";  // 订阅的 Topic
    private static final String USERNAME = "root";  // 用户名
    private static final String PASSWORD = "2583549902@qq.com";  // 密码

    public static void main(String[] args) {
        try {
            // 创建 MQTT 客户端
            MqttClient mqttClient = new MqttClient(BROKER, MqttClient.generateClientId());
            
            // 设置连接选项
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(USERNAME);
            options.setPassword(PASSWORD.toCharArray());
            options.setCleanSession(true);  // 设置为清理会话

            // 设置回调
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("连接丢失，重试中...");
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    // 打印接收到的消息
                    System.out.println("收到主题: " + topic + " 消息: " + new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 消息发送完成的回调（消费者通常不需要关注）
                }
            });

            // 连接到 MQTT 代理服务器
            mqttClient.connect(options);
            System.out.println("已连接到 MQTT 服务器");

            // 订阅主题
            mqttClient.subscribe(TOPIC, 1);
            System.out.println("已订阅主题: " + TOPIC);

        } catch (MqttException e) {
            System.err.println("连接或订阅时出现问题: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
